#include "CodeEditorOverlay.h"

#include <QtGui/QPainter>
#include <QtGui/QTextBlock>

using namespace CodeEdit;
using namespace CodeEdit::Internal;

CodeEditorOverlay::CodeEditorOverlay(CodeEditor *editor)
    : QObject(editor)
    , _editor(editor)
    , _viewport(editor->viewport())
    , _visible(false)
    , _borderWidth(1)
    , _dropShadowWidth(2)
    , _alpha(true)
{
}

void CodeEditorOverlay::update()
{
    if (_visible)
        _viewport->update();
}

void CodeEditorOverlay::setVisible(bool b)
{
    if (_visible != b) {
        _visible = b;
        _viewport->update();
    }
}

void CodeEditorOverlay::clear()
{
    if (!_selections.isEmpty()) {
        _selections.clear();
        update();
    }
}

void CodeEditorOverlay::addOverlaySelection(int begin, int end,
                                            const QColor &fg, const QColor &bg,
                                            uint overlaySelectionFlags,
                                            int verticalBlockSelection)
{
    if (end < begin)
        return;

    QTextDocument *doc = _editor->document();

    OverlaySelection selection;
    selection.fg = fg;
    selection.bg = bg;

    if (overlaySelectionFlags & ExpandBegin) {
        if (begin > 0 && begin < end) { // not empty
            selection.expandBegin = true;
        }
    }

    selection.cursorBegin = QTextCursor(doc->docHandle(), begin);
    selection.cursorEnd = QTextCursor(doc->docHandle(), end);

    if (overlaySelectionFlags & LockSize)
        selection.fixedLength = (end - begin);

    selection.dropShadow = (overlaySelectionFlags & DropShadow);

    selection.verticalBlockSelection = verticalBlockSelection;

    _selections.append(selection);
    update();
}

void CodeEditorOverlay::addOverlaySelection(const QTextCursor &cursor,
                                            const QColor &fg, const QColor &bg,
                                            uint overlaySelectionFlags,
                                            int verticalBlockSelection)
{
    addOverlaySelection(cursor.selectionStart(), cursor.selectionEnd(), fg, bg, overlaySelectionFlags,
                        verticalBlockSelection);
}

QRect CodeEditorOverlay::rect() const
{
    return _viewport->rect();
}

QPainterPath CodeEditorOverlay::createSelectionPath(const QTextCursor &begin, const QTextCursor &end,
                                                    const QRect &clip, int verticalBlockSelection)
{
    if (begin.isNull() || end.isNull() || begin.position() > end.position())
        return QPainterPath();

    QPointF offset = _editor->contentOffset();
    QRect viewportRect = rect();
    QTextDocument *document = _editor->document();

    if (_editor->blockBoundingGeometry(begin.block()).translated(offset).top() > clip.bottom() + 10
     || _editor->blockBoundingGeometry(end.block()).translated(offset).bottom() < clip.top() - 10)
        return QPainterPath(); // nothing of the selection is visible

    QTextBlock block = begin.block();

    bool inSelection = false;

    QVector<QRectF> selection;

    if (begin.position() == end.position()) {
        // special case empty selections
        const QRectF blockGeometry = _editor->blockBoundingGeometry(block);
        QTextLayout *blockLayout = block.layout();
        int pos = begin.position() - begin.block().position();
        QTextLine line = blockLayout->lineForTextPosition(pos);
        QRectF lineRect = line.naturalTextRect();
        int x = line.cursorToX(pos);
        lineRect.setLeft(x - _borderWidth);
        lineRect.setRight(x + _borderWidth);
        selection += lineRect.translated(blockGeometry.topLeft());
    } else {
        for (; block.isValid() && block.blockNumber() <= end.blockNumber(); block = block.next()) {
            if (! block.isVisible())
                continue;

            const QRectF blockGeometry = _editor->blockBoundingGeometry(block);
            QTextLayout *blockLayout = block.layout();

            QTextLine line = blockLayout->lineAt(0);
            bool firstOrLastBlock = false;

            int beginChar = 0;
            if (!inSelection) {
                beginChar = begin.position() - begin.block().position();
                line = blockLayout->lineForTextPosition(beginChar);
                inSelection = true;
                firstOrLastBlock = true;
            } else if (verticalBlockSelection) {
                beginChar = qMin(block.length()-1, begin.position() - begin.block().position());
            } else {
                while (beginChar < block.length() && document->characterAt(block.position() + beginChar).isSpace())
                    ++beginChar;
                if (beginChar == block.length())
                    beginChar = 0;
            }

            int lastLine = blockLayout->lineCount()-1;
            int endChar = -1;
            if (block == end.block()) {
                endChar = end.position() - end.block().position();
                lastLine = blockLayout->lineForTextPosition(endChar).lineNumber();
                inSelection = false;
                firstOrLastBlock = true;
            } else if (verticalBlockSelection) {
                endChar = qMin(block.length()-1, (begin.position() - begin.block().position()) + verticalBlockSelection);
            } else {
                endChar = block.length();
                while (endChar > beginChar && document->characterAt(block.position() + endChar - 1).isSpace())
                    --endChar;
            }

            QRectF lineRect = line.naturalTextRect();
            if (beginChar < endChar) {
                lineRect.setLeft(line.cursorToX(beginChar));
                if (line.lineNumber() == lastLine)
                    lineRect.setRight(line.cursorToX(endChar));
                selection += lineRect.translated(blockGeometry.topLeft());

                for (int lineIndex = line.lineNumber()+1; lineIndex <= lastLine; ++lineIndex) {
                    line = blockLayout->lineAt(lineIndex);
                    lineRect = line.naturalTextRect();
                    if (lineIndex == lastLine)
                        lineRect.setRight(line.cursorToX(endChar));
                    selection += lineRect.translated(blockGeometry.topLeft());
                }
            } else if (!verticalBlockSelection){ // empty lines
                const int emptyLineSelectionSize = 16;
                if (!firstOrLastBlock && !selection.isEmpty()) { // middle
                    lineRect.setLeft(selection.last().left());
                } else if (inSelection) { // first line
                    lineRect.setLeft(line.cursorToX(beginChar));
                } else { // last line
                    if (endChar == 0)
                        break;
                    lineRect.setLeft(line.cursorToX(endChar) - emptyLineSelectionSize);
                }
                lineRect.setRight(lineRect.left() + emptyLineSelectionSize);
                selection += lineRect.translated(blockGeometry.topLeft());
            }

            if (!inSelection)
                break;

            if (blockGeometry.translated(offset).y() > 2*viewportRect.height())
                break;
        }
    }

    if (selection.isEmpty())
        return QPainterPath();

    QVector<QPointF> points;

    const int margin = _borderWidth/2;
    const int extra = 0;

    points += (selection.at(0).topLeft() + selection.at(0).topRight()) / 2 + QPointF(0, -margin);
    points += selection.at(0).topRight() + QPointF(margin+1, -margin);
    points += selection.at(0).bottomRight() + QPointF(margin+1, 0);

    for (int i = 1; i < selection.count()-1; ++i) {
#define MAX3(a,b,c) qMax(a, qMax(b,c))
        qreal x = MAX3(selection.at(i-1).right(),
                       selection.at(i).right(),
                       selection.at(i+1).right()) + margin;

        points += QPointF(x+1, selection.at(i).top());
        points += QPointF(x+1, selection.at(i).bottom());

    }

    points += selection.at(selection.count()-1).topRight() + QPointF(margin+1, 0);
    points += selection.at(selection.count()-1).bottomRight() + QPointF(margin+1, margin+extra);
    points += selection.at(selection.count()-1).bottomLeft() + QPointF(-margin, margin+extra);
    points += selection.at(selection.count()-1).topLeft() + QPointF(-margin, 0);

    for (int i = selection.count()-2; i > 0; --i) {
#define MIN3(a,b,c) qMin(a, qMin(b,c))
        qreal x = MIN3(selection.at(i-1).left(),
                       selection.at(i).left(),
                       selection.at(i+1).left()) - margin;

        points += QPointF(x, selection.at(i).bottom()+extra);
        points += QPointF(x, selection.at(i).top());
    }

    points += selection.at(0).bottomLeft() + QPointF(-margin, extra);
    points += selection.at(0).topLeft() + QPointF(-margin, -margin);

    QPainterPath path;
    const int corner = 4;
    path.moveTo(points.at(0));
    points += points.at(0);
    QPointF previous = points.at(0);
    for (int i = 1; i < points.size(); ++i) {
        QPointF point = points.at(i);
        if (point.y() == previous.y() && qAbs(point.x() - previous.x()) > 2*corner) {
            QPointF tmp = QPointF(previous.x() + corner * ((point.x() > previous.x())?1:-1), previous.y());
            path.quadTo(previous, tmp);
            previous = tmp;
            i--;
            continue;
        } else if (point.x() == previous.x() && qAbs(point.y() - previous.y()) > 2*corner) {
            QPointF tmp = QPointF(previous.x(), previous.y() + corner * ((point.y() > previous.y())?1:-1));
            path.quadTo(previous, tmp);
            previous = tmp;
            i--;
            continue;
        }

        QPointF target = (previous + point) / 2;
        path.quadTo(previous, target);
        previous = points.at(i);
    }
    path.closeSubpath();
    path.translate(offset);
    return path;
}

void CodeEditorOverlay::paintSelection(QPainter *painter, const OverlaySelection &selection)
{

    QTextCursor begin = selection.cursorBegin;
    if (selection.expandBegin)
        begin.setPosition(begin.position() + 1);

    const QTextCursor &end= selection.cursorEnd;
    const QColor &fg = selection.fg;
    const QColor &bg = selection.bg;

    if (begin.isNull() || end.isNull() || begin.position() > end.position())
        return;

    QPainterPath path = createSelectionPath(begin, end, _editor->viewport()->rect(),
                                            selection.verticalBlockSelection);

    painter->save();
    QColor penColor = fg;
    if (_alpha)
        penColor.setAlpha(220);
    QPen pen(penColor, _borderWidth);
    painter->translate(-.5, -.5);

    QRectF pathRect = path.controlPointRect();

    if (bg.isValid()) {
        if (!_alpha || begin.blockNumber() != end.blockNumber()) {
            // gradients are too slow for larger selections :(
            QColor col = bg;
            if (_alpha)
                col.setAlpha(50);
            painter->setBrush(col);
        } else {
            QLinearGradient linearGrad(pathRect.topLeft(), pathRect.bottomLeft());
            QColor col1 = fg.lighter(150);
            col1.setAlpha(20);
            QColor col2 = fg;
            col2.setAlpha(80);
            linearGrad.setColorAt(0, col1);
            linearGrad.setColorAt(1, col2);
            painter->setBrush(QBrush(linearGrad));
        }
    } else {
        painter->setBrush(QBrush());
    }

    painter->setRenderHint(QPainter::Antialiasing);

    if (selection.dropShadow) {
        painter->save();
        QPainterPath shadow = path;
        shadow.translate(_dropShadowWidth, _dropShadowWidth);
        QPainterPath clip;
        clip.addRect(_editor->viewport()->rect());
        painter->setClipPath(clip - path);
        painter->fillPath(shadow, QColor(0, 0, 0, 100));
        painter->restore();
    }

    pen.setJoinStyle(Qt::RoundJoin);
    painter->setPen(pen);
    painter->drawPath(path);
    painter->restore();
}

void CodeEditorOverlay::fillSelection(QPainter *painter,
                                      const OverlaySelection &selection,
                                      const QColor &color)
{
    const QTextCursor &begin = selection.cursorBegin;
    const QTextCursor &end= selection.cursorEnd;
    if (begin.isNull() || end.isNull() || begin.position() > end.position())
        return;

    QPainterPath path = createSelectionPath(begin, end, _editor->viewport()->rect(),
                                            selection.verticalBlockSelection);

    painter->save();
    painter->translate(-.5, -.5);
    painter->setRenderHint(QPainter::Antialiasing);
    painter->fillPath(path, color);
    painter->restore();
}

void CodeEditorOverlay::paint(QPainter *painter, const QRect &clip)
{
    Q_UNUSED(clip);
    for (int i = _selections.size()-1; i >= 0; --i) {
        const OverlaySelection &selection = _selections.at(i);
        if (selection.dropShadow)
            continue;
        if (selection.fixedLength >= 0
            && selection.cursorEnd.position() - selection.cursorBegin.position()
            != selection.fixedLength)
            continue;

        paintSelection(painter, selection);
    }
    for (int i = _selections.size()-1; i >= 0; --i) {
        const OverlaySelection &selection = _selections.at(i);
        if (!selection.dropShadow)
            continue;
        if (selection.fixedLength >= 0
            && selection.cursorEnd.position() - selection.cursorBegin.position()
            != selection.fixedLength)
            continue;

        paintSelection(painter, selection);
    }
}

void CodeEditorOverlay::fill(QPainter *painter, const QColor &color, const QRect &clip)
{
    Q_UNUSED(clip);
    for (int i = _selections.size()-1; i >= 0; --i) {
        const OverlaySelection &selection = _selections.at(i);
        if (selection.dropShadow)
            continue;
        if (selection.fixedLength >= 0
            && selection.cursorEnd.position() - selection.cursorBegin.position()
            != selection.fixedLength)
            continue;

        fillSelection(painter, selection, color);
    }
    for (int i = _selections.size()-1; i >= 0; --i) {
        const OverlaySelection &selection = _selections.at(i);
        if (!selection.dropShadow)
            continue;
        if (selection.fixedLength >= 0
            && selection.cursorEnd.position() - selection.cursorBegin.position()
            != selection.fixedLength)
            continue;

        fillSelection(painter, selection, color);
    }
}

bool CodeEditorOverlay::hasCursorInSelection(const QTextCursor &cursor) const
{
    for (int i = 0; i < _selections.size(); ++i) {
        const OverlaySelection &selection = _selections.at(i);
        if (cursor.position() > selection.cursorBegin.position()
            && cursor.position() <= selection.cursorEnd.position())
            return true;
    }
    return false;
}
